package com.ruoyi.system.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.constant.ErrorCode;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.ExceptionCast;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.domain.ImAppInfoVo;
import com.ruoyi.system.domain.ImUserGroup;
import com.ruoyi.system.domain.ImUserMessage;
import com.ruoyi.system.domain.dto.ImUserListDto;
import com.ruoyi.system.domain.dto.ImUserPasswordDto;
import com.ruoyi.system.domain.dto.ImUserUpdateDto;
import com.ruoyi.system.domain.vo.ImUserListVo;
import com.ruoyi.system.im.TencentCloudImUtil;
import com.ruoyi.system.mapper.ImUserGroupMapper;
import com.ruoyi.system.mapper.ImUserMessageMapper;
import com.ruoyi.system.service.IImUserMessageService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.ImUserMapper;
import com.ruoyi.system.domain.ImUser;
import com.ruoyi.system.service.IImUserService;

import static com.ruoyi.common.utils.PageUtils.getDataTable;

/**
 * 【请填写功能名称】Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-03-30
 */
@Service
public class ImUserServiceImpl extends ServiceImpl<ImUserMapper, ImUser> implements IImUserService
{
    @Autowired
    private ImUserMapper imUserMapper;

    @Autowired
    private ImUserMessageMapper imUserMessageMapper;

    @Autowired
    private ImUserGroupMapper imUserGroupMapper;

    @Autowired
    private IImUserMessageService imUserMessageService;

    /**
     * 查询【请填写功能名称】
     * 
     * @param id 【请填写功能名称】主键
     * @return 【请填写功能名称】
     */
    @Override
    public ImUser selectImUserById(Long id)
    {
        return imUserMapper.selectImUserById(id);
    }

    /**
     * 查询【请填写功能名称】列表
     * 
     * @param imUser 【请填写功能名称】
     * @return 【请填写功能名称】
     */
    @Override
    public List<ImUser> selectImUserList(ImUser imUser)
    {
        return imUserMapper.selectImUserList(imUser);
    }

    /**
     * 新增【请填写功能名称】
     * 
     * @param imUser 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int insertImUser(ImUser imUser)
    {
        imUser.setCreateTime(DateUtils.getNowDate());
        return imUserMapper.insertImUser(imUser);
    }

    /**
     * 修改【请填写功能名称】
     * 
     * @param imUser 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int updateImUser(ImUser imUser)
    {
        return imUserMapper.updateImUser(imUser);
    }

    /**
     * 批量删除【请填写功能名称】
     * 
     * @param ids 需要删除的【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteImUserByIds(Long[] ids)
    {
        return imUserMapper.deleteImUserByIds(ids);
    }

    /**
     * 删除【请填写功能名称】信息
     * 
     * @param id 【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteImUserById(Long id)
    {
        return imUserMapper.deleteImUserById(id);
    }

    @Autowired
    private TencentCloudImUtil tencentCloudImUtil;

    @Override
    public AjaxResult addImUser(ImUser imUser) {
        LambdaQueryWrapper<ImUser> imUserLambdaQueryWrapper=new LambdaQueryWrapper<>();
        imUserLambdaQueryWrapper.eq(ImUser::getUserId,imUser.getUserId());
        ImUser user = imUserMapper.selectOne(imUserLambdaQueryWrapper);
        if (ObjectUtils.isNotEmpty(user)){
            ExceptionCast.cast(ErrorCode.USER_ID_IS_USER);
        }
        String s = tencentCloudImUtil.accountImport(imUser.getUserId(), imUser.getNickName());
        System.out.println(s);
        Map map = JSON.parseObject(s, Map.class);

        if ("OK".equals(map.get("ActionStatus"))){
            imUser.setCreateTime(new Date());
            imUserMapper.insert(imUser);
            return AjaxResult.success();
        }else {
            return AjaxResult.error((String) map.get("ErrorInfo"));
        }
    }

    @Override
    public TableDataInfo userList(ImUserListDto listDto) throws ParseException {
        LambdaQueryWrapper<ImUser> imUserLambdaQueryWrapper=new LambdaQueryWrapper<>();
        imUserLambdaQueryWrapper.eq(ObjectUtils.isNotEmpty(listDto.getPhoneNumber()),ImUser::getPhoneNumber,listDto.getPhoneNumber());
        imUserLambdaQueryWrapper.like(ObjectUtils.isNotEmpty(listDto.getNickName()),ImUser::getNickName,listDto.getNickName());
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (ObjectUtils.isNotEmpty(listDto.getStartTime())&&ObjectUtils.isNotEmpty(listDto.getEndTime())) {
            if (listDto.getStartTime().equals(listDto.getEndTime())) {
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(listDto.getEndTime());
                calendar.set(Calendar.HOUR, 23);
                calendar.set(Calendar.MINUTE, 59);
                calendar.set(Calendar.SECOND, 59);
                Date end = calendar.getTime();
                imUserLambdaQueryWrapper.between(ImUser::getCreateTime, listDto.getStartTime(), end);
            } else {
                imUserLambdaQueryWrapper.between(ImUser::getCreateTime, listDto.getStartTime(), listDto.getEndTime());
            }
        } else if (ObjectUtils.isEmpty(listDto.getStartTime()) && ObjectUtils.isNotEmpty(listDto.getEndTime())) {
            String timeStr= "2000-01-01 00:00:00";
            Date start = sdf.parse(timeStr);
            imUserLambdaQueryWrapper.between(ImUser::getCreateTime, start, listDto.getEndTime());
        } else if (ObjectUtils.isNotEmpty(listDto.getStartTime()) && ObjectUtils.isEmpty(listDto.getEndTime())) {
            String timeStr="3000-01-01 00:00:00";
            Date end=sdf.parse(timeStr);
            imUserLambdaQueryWrapper.between(ImUser::getCreateTime,listDto.getStartTime(),end);
        }

        List<ImUser> imUsers = imUserMapper.selectList(imUserLambdaQueryWrapper);

        long total = new PageInfo<>(imUsers).getTotal();
        List<ImUserListVo> list=imUsers.stream().map(x->{
            ImUserListVo listVo = BeanUtil.toBean(x, ImUserListVo.class);
            Integer userFriendNum = tencentCloudImUtil.getUserFriendNum(x.getUserId());
            listVo.setFriendNum(userFriendNum);

            Integer userGroupNum = tencentCloudImUtil.getUserGroupNum(x.getUserId());
            listVo.setGroupNum(userGroupNum);

            return listVo;
        }).collect(Collectors.toList());
        return getDataTable(list,total);
    }

    @Override
    public void updateUser(ImUserUpdateDto updateDto) {
        LambdaQueryWrapper<ImUser> imUserLambdaQueryWrapper=new LambdaQueryWrapper<>();
        imUserLambdaQueryWrapper.eq(ImUser::getUserId,updateDto.getUserId());
        ImUser imUser = imUserMapper.selectOne(imUserLambdaQueryWrapper);
        imUser .setEmail(updateDto.getEmail());
        imUser.setPhoneNumber(updateDto.getPhoneNumber());
        imUser.setNickName(updateDto.getNickName());
        imUser.setGender(updateDto.getGender());
        imUserMapper.updateImUser(imUser);
    }

    @Override
    public void deleteUser(Long id) {
        ImUser imUser = imUserMapper.selectById(id);
        Boolean flag = tencentCloudImUtil.deleteUser(imUser.getUserId());
        if (flag) {
            imUserMapper.deleteById(id);
        }else {
            ExceptionCast.cast(ErrorCode.DELETE_USER_FAIL);
        }

    }

    @Override
    public void userPassword(ImUserPasswordDto passwordDto) {
        ImUser imUser = imUserMapper.selectById(passwordDto.getId());
        if (!passwordDto.getPassword().equals(passwordDto.getConfirmPassword())){
            ExceptionCast.cast(ErrorCode.PASSWORD_CONFIRM_IS_ERROR);
        }
        imUser.setPassword(passwordDto.getPassword());
        imUserMapper.updateById(imUser);
    }

    @Override
    public Map<String, Integer> homePage() {
        Map<String,Integer> map=new HashMap<>();
        Long userNum = imUserMapper.selectCount(null);
        Long groupNum = imUserGroupMapper.selectCount(null);
        LambdaQueryWrapper<ImUserMessage> imUserMessageLambdaQueryWrapper=new LambdaQueryWrapper<>();
        imUserMessageLambdaQueryWrapper.eq(ImUserMessage::getIsDelete,0);
        Long messageNum = imUserMessageMapper.selectCount(imUserMessageLambdaQueryWrapper);

        List<ImAppInfoVo> appInfo = tencentCloudImUtil.getAppInfo();
        System.out.println(appInfo);
        List<ImAppInfoVo> imAppInfoVos = JSON.parseArray(JSONObject.toJSONString(appInfo), ImAppInfoVo.class);
        Map<String, ImAppInfoVo> dateAppInfo = imAppInfoVos.stream().collect(Collectors.toMap(ImAppInfoVo::getDate, x -> x));
        LocalDate yesterday = LocalDate.now().minusDays(1);
        // 格式化日期为指定格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        String formattedYesterday = yesterday.format(formatter);
        //今日注册 今日登录
        ImAppInfoVo imAppInfoVo = dateAppInfo.get(formattedYesterday);
        map.put("todayRegistNum", Integer.valueOf(imAppInfoVo.getRegistUserNumOneDay()));
        map.put("todayLoginNum",Integer.valueOf(imAppInfoVo.getLoginUserNum()));
        //三日新增 七日新增
        Integer threeDayRegistNum=0;
        Integer sevenDayRegistNum=0;
        Integer sevenDayLoginNum=0;
        for (int i = 1; i <= 7; i++) {
            LocalDate day = LocalDate.now().minusDays(i);
            String dayStr = day.format(formatter);
            ImAppInfoVo infoVo = dateAppInfo.get(dayStr);
            if (i<=3) {
                threeDayRegistNum = threeDayRegistNum + Integer.parseInt(infoVo.getRegistUserNumOneDay());
            }
            sevenDayRegistNum=sevenDayRegistNum+Integer.parseInt(infoVo.getRegistUserNumOneDay());
            sevenDayLoginNum=sevenDayLoginNum+Integer.parseInt(infoVo.getLoginUserNum());
        }
        map.put("threeDayRegistNum",threeDayRegistNum);
        map.put("sevenDayRegistNum",sevenDayRegistNum);
        map.put("sevenDayLoginNum",sevenDayLoginNum);
        //月活跃
        int sum = imAppInfoVos.stream().mapToInt(x -> Integer.parseInt(x.getLoginUserNum())).sum();
        map.put("thirtyDayLoginNum",sum);


        map.put("userNum", Math.toIntExact(userNum));
        map.put("groupNum",Math.toIntExact(groupNum));
        map.put("messageNum",Math.toIntExact(messageNum));
        return map;
    }

    @Override
    public void deleteContract() {
        //删除数据库单聊记录
        UpdateWrapper<ImUserMessage> userMessageUpdateWrapper=new UpdateWrapper<>();
        userMessageUpdateWrapper.lambda().eq(ImUserMessage::getIsDelete,0);
        userMessageUpdateWrapper.set("is_delete",1);
        imUserMessageService.update(userMessageUpdateWrapper);

        //删除腾讯云端单聊记录
        List<ImUser> imUsers = imUserMapper.selectList(null);
        for (ImUser imUser : imUsers) {
            List<String> userFriendList = tencentCloudImUtil.getUserFriendList(imUser.getUserId());
            if (userFriendList.size()>0) {
                tencentCloudImUtil.deleteUserContact(imUser.getUserId(), userFriendList);
            }
        }

        //删除腾讯云端群聊记录
        List<ImUserGroup> imUserGroups = imUserGroupMapper.selectList(null);
        for (ImUserGroup imUserGroup : imUserGroups) {
            tencentCloudImUtil.deleteGroupContract(imUserGroup.getGroupId());
        }
    }
}
